//index.js
//获取应用实例
const app = getApp()
const utils = require("../../utils/util.js");
import apis from '../../utils/apis'
import webSocket from '../../socket/socket.js'
import sessionUtils from '../../utils/sessions-utils.js'
import messageStorage from '../../utils/message-storage.js'

// import ChatSession from '../../entity/ChatSession.js'
Page({
  data: {
    sessionList: [],
    isLogin: false,
    isShowContacts: false,
    contactsList: [],
    userInfo: {},
    flushImageRotate: 0,
    isAuthorUserInfo:false,
    socketConnected:false,
    isShowErrorDialog:false,
  },

  /**
   * 用户登录，成功后添加用户
   */
  userLogin() {
    wx.showLoading({
      title: '用户登录中...',
    })
    var _this = this;
    wx.login({
      complete: (wxlogin) => {
        apis.login(wxlogin.code).then((res) => {
          this.setData({
            isLogin:true
          })
          var openId = res.data.data.openid;
          var userInfo = this.data.userInfo;
          var newInfo = { "nickName": userInfo.nickName, "id": openId, "profileUrl": userInfo.avatarUrl }
          app.globalData.myUserInfo = newInfo
          apis.addUser(newInfo, openId)
          webSocket.connectServer(openId)
     
        }).catch((res)=>{
         this.showLoginDialog("登录失败:"+res.errMsg);
        })
        this.listContack();
      },
    })

    
    wx.event.on('create-session', (e) => {
      _this.handlerSession(e)

    })

    wx.event.on("socket-events",(e)=>{
      if(this.data.isShowErrorDialog){
        return
      }
      if(e.msg=="close"){
        console.log("xxxxxxxxxxxxxxxxxxx")
        this.setData({
          socketConnected:false,
          isShowErrorDialog:true
        })
        wx.showModal({
          title:"提示",
          content:"服务器连接失败，请重新连接",
          success(res){
            _this.setData({
              isShowErrorDialog:false
            })
          }
        })
    
      }else if(e.msg=="connected"){
        this.setData({
          socketConnected:true
        })
      }

    })
 
    wx.event.on('receive-message', (e) => {
      var messageInfo = e
      /**
       * 处理界面，返回当前会话列表，并储存
       */
         _this.handlerSession(messageInfo);
   


      /**
       * 创建消息记录，并储存
       */
      var newMessageItem = messageStorage.createMessageItem(messageInfo.msg, false)
      messageStorage.storageMessage(messageInfo.fromId, newMessageItem)

      wx.event.emit(messageInfo.fromId, newMessageItem)

    })

    wx.event.on('system-message', (e) => {
      if (e.msg == "flush-user") {
        this.listContack();
      }
    })
  },
  showLoginDialog:function(msg){
    wx.hideLoading({
      complete: (res) => {},
    })
      wx.showModal({
        title:"提示",
        content:msg,
      })   
  },
  /**
   * 负责更新列表
   * @param {消息信息} messageInfo 
   */
  handlerSession: function (messageInfo) {
    var senderUserInfo = sessionUtils.getUserInfoWithOpenId(messageInfo.fromId)
    var chatSession = sessionUtils.createChatSession(senderUserInfo, messageInfo.msg);

    /**
     * 如果当前列表中没有这个好友的会话。
     */
    if ((this.data.sessionList.find((item) => item.userInfo.id == chatSession.userInfo.id)) == undefined) {
      var tempSession = this.data.sessionList;
      if (getCurrentPages().length == 1) {
        chatSession.messageCount = 1
      }
      tempSession.unshift(chatSession)
      this.setData({
        sessionList: tempSession
      })
      messageStorage.storageSession(this.data.sessionList);
      return this.data.sessionList
    }
    /**
     * 更新消息
     */
    var index = this.data.sessionList.findIndex((item) => item.userInfo.id == chatSession.userInfo.id)
    var session = this.data.sessionList[index];
    /**
     * 如果不在其他页
     */

    if ( app.globalData.currentSessionOpenId=="") {
      session.messageCount += 1;
    }
    session.msg =messageInfo.msg
    this.data.sessionList[index] = session


    this.data.sessionList[0] =  this.data.sessionList.splice(index, 1,  this.data.sessionList[0])[0]
    this.setData({
      sessionList: this.data.sessionList
    })
    messageStorage.storageSession(this.data.sessionList);
    return this.data.sessionList;
  },

  onLoad: function (options) {
    
    this.readSession();
    var _this = this;
    /**
     * 是否存有用户权限
     */
    utils.testAuth("scope.userInfo", (res) => {
      if (res == true) {
        this.setData({
          isAuthorUserInfo: true
        })
        /**
         * 获取用户信息
         */
        wx.getUserInfo({
          complete: (res) => {
            _this.onUserSuccess(res.userInfo)
          },
        })


      } else {
        this.setData({
          isAuthorUserInfo: false
        })
      }
    })
    // 
  },

  /**
   * 获取系统所有用户
   */
  listContack() {
    var _this = this
    apis.listUser().then((res) => {
      this.setData({
        flushImageRotate: false
      })
      var list = res.data.data;
      app.globalData.contactList = list;
      _this.setData({
        contactsList: list
      })
    })
  },
  onShow(options) {

  },
  /**
   * 用户信息获取成功回调
   * @param {用户信息}} e 
   */
  onUserSuccess: function (e) {
    app.globalData.userInfo = e
    this.setData({
      userInfo: e,
      hasUserInfo: true,
      isAuthorUserInfo: true
    })
    this.userLogin()
  },

  /**
   * 联系人单机函数
   * @param {}} e 
   */
  checkState:function(){
    if(!this.data.isLogin){
      this.userLogin()
      return false;
    }else if(!this.data.socketConnected){
      webSocket.connectServer()
      return false;
    }
    return true;
  },
  onContactClick(e) {
    if(!this.checkState()){
      return false;
    }
    this.existSessionOpenid()
    var index = e.currentTarget.dataset.index;
    var userInfo = this.data.contactsList[index];

    app.globalData.currentClickUserInfo = sessionUtils.createChatSession(userInfo,"");
    wx.navigateTo({
      url: '/pages/chat/chat'
    })
  },

  /**
   * 会话单机函数
   * @param {} e 
   */
  onSessionClick(e) {
    if(!this.checkState()){
      return
    }
    if (this.data.isShowContacts) {
      this.closeContacts(false)
      return;
    }
    var id = e.currentTarget.dataset.id;
    app.globalData.currentClickUserInfo=this.data.sessionList.find((item)=>item.userInfo.id==id);
    console.log( app.globalData.currentClickUserInfo )
    this.clearSessionMessageCount(id)
    wx.navigateTo({
      url: '/pages/chat/chat'
    })
  },
  touchHandler(id) {
    wx.navigateTo({
      url: '../chat/chat',
    })
  },
  bindGetUserInfo: function (e) {
    this.onUserSuccess(JSON.parse(e.detail.rawData))
  },

  chatListTouchMove: function (params) {
    this.closeContacts(false)

  },
  /**
   * 显示联系人列表
   */
  showContacts: function (params) {

    this.closeContacts(true)
  },
  closeContacts: function (status) {
    this.setData({
      isShowContacts: status
    })
  },
  flushContacts: function (params) {
    this.setData({
      flushImageRotate: true
    })
    this.listContack()
  },
  clearSessionMessageCount(openId) {
    var tempSessionList = this.data.sessionList;
    tempSessionList.forEach((item) => {
      if (item.userInfo.id == openId) {
        item.messageCount = 0
      }
    })
    messageStorage.storageSession(tempSessionList)
    this.readSession()
  },
  readSession() {
    this.setData({
      sessionList: messageStorage.getSession()
    })
  },
  existSessionOpenid(openId) {
    var result = -1;
    for (let [index, elem] of this.data.sessionList.entries()) {
        if(elem.userInfo.id==openId){
          result=index;
        }
    }
    return result;
  },
})
